<!-- views/Register.vue -->
<template>
  <div>
    <!-- 标题栏 -->
    <mt-header title="用户登录">
      <mt-button icon="back" slot="left"></mt-button>
      <router-link to='/register' slot="right">注册</router-link>
    </mt-header>
    <!-- 表单组件 -->
    <mt-field type="text" label="用户名" 
              v-model="name" :state="nameState"
              placeholder="请输入用户名"
              @blur.native.capture="checkName" />
    <mt-field type="password" label="密码" 
              v-model="pwd" :state="pwdState"
              placeholder="请输入密码"
              @blur.native.capture="checkPwd" />
    <mt-button type="primary" size="large"
      @click="checkForm">
      登录
    </mt-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: '',       // 双向数据绑定 用户名输入框
      nameState: '',   // 处理用户名输入框的状态的动态更新
      pwd: '',
      pwdState: ''
    }
  },
  methods: {

    // 验证用户名
    checkName(){
      let reg = /^\w{6,15}$/;
      if(reg.test(this.name)){ // 验证成功
        this.nameState = "success";
        return true;
      }else{  // 验证失败
        this.nameState = "error";
        return false;
      }
    },
    // 验证密码
    checkPwd(){
      let reg = /^\d{6}$/;
      if(reg.test(this.pwd)){ // 验证成功
        this.pwdState = "success";
        return true;
      }else{  // 验证失败
        this.pwdState = "error";
        return false;
      }
    },
  
    checkForm(){  // 事件处理函数，处理点击按钮验证表单
      if(this.checkName() && this.checkPwd()){
        console.log('验证成功，发送请求，执行登录业务...');

        //发送登录请求 post
        this.axios.post('/login',`username=${this.name}&password=${this.pwd}`).then(res=>{
          // console.log(res);
          if(res.data.code==200){
            this.$toast({
              message:'登录成功',
              position:'bottom',
              duration: 3000
            })
            
            //修改vuex的登录状态
            this.$store.commit('loginok',this.name);
            //将islogin 与 username存入sessionStorage
            sessionStorage.setItem('islogin',true);
            sessionStorage.setItem('username',this.name);

            this.$router.push('/')
          }else if(res.data.code==201){
            this.$toast({
              message:'用户名或密码不正确，请重新输入',
              position:'bottom',
              duration: 3000
            })
          }
        })
      }
    }
  }
}
</script>



